import { Component, Vue } from 'vue-property-decorator';
// 倒计时
@Component
export default class CountDown extends Vue {
    public downTask: any = {};
    public downTime: string = '00:00';
    public countTime: number = 0;
    public timerID: any = null;
    constructor() {
        super();
    }

    /**
     * // 倒计时
     * @param timestamp 秒
     * @param callback 倒计时结束回调
     */
    downTimeStart(timestamp = 0, callback?: Function, spar = '：'): void {
        if (timestamp.toString().length == 13) timestamp = Math.round(timestamp / 1000);
        if (timestamp <= 0) this.clearTimer();
        this.formantTime(timestamp, spar);
        this.timerID = setInterval(() => {
            timestamp--;
            this.countTime = timestamp
            if (timestamp <= 5) {
                this.$emit('about', timestamp);
            }
            if (timestamp <= 0) {
                this.clearTimer();
                if (callback) callback();
                return;
            }
            this.formantTime(timestamp, spar);
        }, 1000);
    }

    // 格式化时间
    formantTime(timestamp: number, spar: string = '：') {
        let day: number | string = 0;
        let hour: number | string = 0;
        let min: number | string = 0;
        let second: number | string = 0;
        const d = Math.floor(timestamp / 60 / 60 / 24);
        const h = Math.floor((timestamp / 60 / 60) % 24);
        const m = Math.floor((timestamp / 60) % 60);
        const s = Math.floor(timestamp % 60);
        day = d < 10 ? '0' + d : d;
        hour = h < 10 ? '0' + h : h;
        min = m < 10 ? '0' + m : m;
        second = s < 10 ? '0' + s : s;
        if (day != '00' || Number(day) != 0) {
            this.downTime =  day+spar+hour+spar+min+spar+second;
        } else if (hour != '00' || Number(hour) != 0) {
            this.downTime =  hour+spar+min+spar+second;
        } else {
            this.downTime  = min+spar+second;
        }
    }

    clearTimer(name?: string) {
        if (name && this.downTask[name]) delete this.downTask[name]
        if (this.timerID) {
            // 清除定时器
            clearInterval(this.timerID);
            this.timerID = null;
        }
    }

    beforeDestroy() {
        this.clearTimer();
    }
}
